<!DOCTYPE html>
<html prefix="og: http://ogp.me/ns# article: http://ogp.me/ns/article# " lang="en">
<head>
<meta charset="utf-8">
<meta name="description" content="Tj2's Blog">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>绿萝间 (old posts, page 3) | 绿萝间</title>
<link href="assets/css/all-nocdn.css" rel="stylesheet" type="text/css">
<link href="assets/css/ipython.min.css" rel="stylesheet" type="text/css">
<link href="assets/css/nikola_ipython.css" rel="stylesheet" type="text/css">
<meta name="theme-color" content="#5670d4">
<meta name="generator" content="Nikola (getnikola.com)">
<link rel="alternate" type="application/rss+xml" title="RSS" href="rss.xml">
<link rel="canonical" href="https://muxuezi.github.io/index-3.html">
<link rel="prev" href="index-4.html" type="text/html">
<link rel="next" href="index-2.html" type="text/html">
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
    tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"] ],
        displayMath: [ ['$$','$$'], ["\\[","\\]"] ],
        processEscapes: true
    },
    displayAlign: 'center', // Change this to 'center' to center equations.
    "HTML-CSS": {
        styles: {'.MathJax_Display': {"margin": 0}}
    }
});
</script><!--[if lt IE 9]><script src="assets/js/html5.js"></script><![endif]-->
</head>
<body>
<a href="#content" class="sr-only sr-only-focusable">Skip to main content</a>

<!-- Menubar -->

<nav class="navbar navbar-inverse navbar-static-top"><div class="container">
<!-- This keeps the margins nice -->
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-navbar" aria-controls="bs-navbar" aria-expanded="false">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="https://muxuezi.github.io/">

                <span id="blog-title">绿萝间</span>
            </a>
        </div>
<!-- /.navbar-header -->
        <div class="collapse navbar-collapse" id="bs-navbar" aria-expanded="false">
            <ul class="nav navbar-nav">
<li>
<a href="archive.html">Archive</a>
                </li>
<li>
<a href="categories/">Tags</a>
                </li>
<li>
<a href="rss.xml">RSS feed</a>

                
            </li>
</ul>
<ul class="nav navbar-nav navbar-right"></ul>
</div>
<!-- /.navbar-collapse -->
    </div>
<!-- /.container -->
</nav><!-- End of Menubar --><div class="container" id="content" role="main">
    <div class="body-content">
        <!--Body content-->
        <div class="row">
            
            

    
<div class="postindex">
    <article class="h-entry post-text"><header><h1 class="p-name entry-title"><a href="posts/permission-to-be-human.html" class="u-url">permission-to-be-human</a></h1>
        <div class="metadata">
            <p class="byline author vcard"><span class="byline-name fn">
                Tao Junjie
            </span></p>
            <p class="dateline"><a href="posts/permission-to-be-human.html" rel="bookmark"><time class="published dt-published" datetime="2010-01-01T13:44:27+08:00" title="2010-01-01 13:44">2010-01-01 13:44</time></a></p>
        </div>
    </header><div class="p-summary entry-summary">
    <div>
<p></p>
<a title="幸福课" href="http://v.163.com/movie/2006/1/3/T/M6HV755O6_M6HV8QB3T.html" target="_blank">幸福课</a>
——计划整理文字内容，便于查阅。</div>
    </div>
    </article><article class="h-entry post-text"><header><h1 class="p-name entry-title"><a href="posts/pic-matplotlib-images-in-terminal.html" class="u-url">pic-matplotlib-images-in-terminal</a></h1>
        <div class="metadata">
            <p class="byline author vcard"><span class="byline-name fn">
                Tao Junjie
            </span></p>
            <p class="dateline"><a href="posts/pic-matplotlib-images-in-terminal.html" rel="bookmark"><time class="published dt-published" datetime="2010-01-01T13:44:27+08:00" title="2010-01-01 13:44">2010-01-01 13:44</time></a></p>
        </div>
    </header><div class="p-summary entry-summary">
    <div>
<p></p>
<p>How To Generate Python/Matplotlib Images Without Having A Window Appear
在debian终端直接生产png文件，然后在其他环境打开。</p>
<p>The easiest way to do this is use a non-interactive backend such as Agg (for PNGs), PDF, SVG or PS. In your figure-generating script, just call the matplotlib.use() directive before importing pylab or pyplot:</p>
<p>import matplotlib</p>
<p>matplotlib.use('Agg')  #必须在pyplot之前使用</p>
<p>import matplotlib.pyplot as plt</p>
<p>plt.plot([1,2,3])</p>
<p>plt.savefig('myfig')</p>
</div>
    </div>
    </article><article class="h-entry post-text"><header><h1 class="p-name entry-title"><a href="posts/prolog-for-8queens.html" class="u-url">prolog-for-8queens</a></h1>
        <div class="metadata">
            <p class="byline author vcard"><span class="byline-name fn">
                Tao Junjie
            </span></p>
            <p class="dateline"><a href="posts/prolog-for-8queens.html" rel="bookmark"><time class="published dt-published" datetime="2010-01-01T13:44:27+08:00" title="2010-01-01 13:44">2010-01-01 13:44</time></a></p>
        </div>
    </header><div class="p-summary entry-summary">
    <div>
<p></p>
<p>prolog in 7W7L</p>
<p class="more"><a href="posts/prolog-for-8queens.html">Read more…</a></p>
</div>
    </div>
    </article><article class="h-entry post-text"><header><h1 class="p-name entry-title"><a href="posts/prolog-for-sudoku.html" class="u-url">prolog-for-sudoku</a></h1>
        <div class="metadata">
            <p class="byline author vcard"><span class="byline-name fn">
                Tao Junjie
            </span></p>
            <p class="dateline"><a href="posts/prolog-for-sudoku.html" rel="bookmark"><time class="published dt-published" datetime="2010-01-01T13:44:27+08:00" title="2010-01-01 13:44">2010-01-01 13:44</time></a></p>
        </div>
    </header><div class="p-summary entry-summary">
    <div>
<p></p>
<p>长见识了，也许是新方向，附加转html为矩阵的python</p>
<p class="more"><a href="posts/prolog-for-sudoku.html">Read more…</a></p>
</div>
    </div>
    </article><article class="h-entry post-text"><header><h1 class="p-name entry-title"><a href="posts/pyperclip-clipboard-content.html" class="u-url">pyperclip-clipboard-content</a></h1>
        <div class="metadata">
            <p class="byline author vcard"><span class="byline-name fn">
                Tao Junjie
            </span></p>
            <p class="dateline"><a href="posts/pyperclip-clipboard-content.html" rel="bookmark"><time class="published dt-published" datetime="2010-01-01T13:44:27+08:00" title="2010-01-01 13:44">2010-01-01 13:44</time></a></p>
        </div>
    </header><div class="p-summary entry-summary">
    <div>
<p></p>
<p>import pyperclip
处理一下不能获取的网页节点</p>
<p>&lt;input name="result" id="result" type="text" value=""&gt;</p>
<h2>shadow-root (user-agent)</h2>
<p>&lt;div id="inner-editor"26 /&gt;</p>
<p>shadow-root是selenium无法读出的。</p>
<p>解决方法：</p>
<p>定位 input name="result" type="text" /&gt; 通过pyperclip获取剪贴板内容，为了保证准确性多复制几次</p>
<p>ft = self.driver.find_element_by_name("result")</p>
<p>def copyn(x):</p>
<p>ft.send_keys(Keys.CONTROL, 'a')</p>
<p>ft.send_keys(Keys.CONTROL, 'c')</p>
<p>map(copyn,range(2))</p>
<p>return pyperclip.paste()</p>
<p>网速不稳定的时候，time.sleep(2)缓两秒比较靠谱</p>
<p>网络数据处理效果依赖网速</p>
</div>
    </div>
    </article><article class="h-entry post-text"><header><h1 class="p-name entry-title"><a href="posts/python-2-vs-3.html" class="u-url">python-2-vs-3</a></h1>
        <div class="metadata">
            <p class="byline author vcard"><span class="byline-name fn">
                Tao Junjie
            </span></p>
            <p class="dateline"><a href="posts/python-2-vs-3.html" rel="bookmark"><time class="published dt-published" datetime="2010-01-01T13:44:27+08:00" title="2010-01-01 13:44">2010-01-01 13:44</time></a></p>
        </div>
    </header><div class="p-summary entry-summary">
    <div>
<p></p>
<p>Google上search了一下3.x和2.x的区别。
1.性能 </p>
<p>Py3.0运行 pystone benchmark的速度比Py2.5慢30%。Guido认为Py3.0有极大的优化空间，在字符串和整形操作上可 </p>
<p>以取得很好的优化结果。 </p>
<p>Py3.1性能比Py2.5慢15%，还有很大的提升空间。 </p>
<p>2.编码 </p>
<p>Py3.X源码文件默认使用utf-8编码，这就使得以下代码是合法的： 
    &gt;&gt;&gt; 中国 = 'china' 
    &gt;&gt;&gt;print(中国) 
    china 
3. 语法 </p>
<p>1）去除了，全部改用!= </p>
<p>2）去除``，全部改用repr() </p>
<p>3）关键词加入as 和with，还有True,False,None </p>
<p>4）整型除法返回浮点数，要得到整型结果，请使用// </p>
<p>5）加入nonlocal语句。使用noclocal x可以直接指派外围（非全局）变量 </p>
<p>6）去除print语句，加入print()函数实现相同的功能。同样的还有 exec语句，已经改为exec()函数 
   例如： 
     2.X: print "The answer is", 2<em>2 
     3.X: print("The answer is", 2</em>2) 
     2.X: print x,                              # 使用逗号结尾禁止换行 
     3.X: print(x, end=" ")                     # 使用空格代替换行 
     2.X: print                                 # 输出新行 
     3.X: print()                               # 输出新行 
     2.X: print &gt;&gt;sys.stderr, "fatal error" 
     3.X: print("fatal error", file=sys.stderr) 
     2.X: print (x, y)                          # 输出repr((x, y)) 
     3.X: print((x, y))                         # 不同于print(x, y)! 
7）改变了顺序操作符的行为，例如x<y bool int an integer : c>&gt;&gt; 0666 
     438 
     &gt;&gt;&gt; oct(438) 
     '0666' 
   3.X这样： 
     &gt;&gt;&gt; 0666 
     SyntaxError: invalid token (<pyshell>, line 1) 
     &gt;&gt;&gt; 0o666 
     438 
     &gt;&gt;&gt; oct(438) 
     '0o666' 
11）增加了 2进制字面量和bin()函数 
    &gt;&gt;&gt; bin(438) 
    '0b110110110' 
    &gt;&gt;&gt; _438 = '0b110110110' 
    &gt;&gt;&gt; _438 
    '0b110110110' 
12）扩展的可迭代解包。在Py3.X 里，a, b, <em>rest = seq和 </em>rest, a = seq都是合法的，只要求两点：rest是list </pyshell></y></p>
<p>对象和seq是可迭代的。 </p>
<p>13）新的super()，可以不再给super()传参数， 
    &gt;&gt;&gt; class C(object): 
          def <strong>init</strong>(self, a): 
             print('C', a) 
    &gt;&gt;&gt; class D(C): 
          def <strong>init(self, a): 
             super().__init</strong>(a) # 无参数调用super() 
    &gt;&gt;&gt; D(8) 
    C 8 
    &lt;<strong>main</strong>.d object at&gt; 
14）新的metaclass语法： 
    class Foo(<em>bases, </em>*kwds): 
      pass 
15）支持class decorator。用法与函数decorator一样： 
    &gt;&gt;&gt; def foo(cls_a): 
          def print_func(self): 
             print('Hello, world!') 
          cls_a.print = print_func 
          return cls_a 
    &gt;&gt;&gt; @foo 
    class C(object): 
      pass 
    &gt;&gt;&gt; C().print() 
    Hello, world! 
class decorator可以用来玩玩狸猫换太子的大把戏。更多请参阅PEP 3129 </p>
<ol>
<li>字符串和字节串 </li>
</ol>
<p>1）现在字符串只有str一种类型，但它跟2.x版本的unicode几乎一样。</p>
<p>2）关于字节串，请参阅“数据类型”的第2条目 </p>
<p>5.数据类型 </p>
<p>1）Py3.X去除了long类型，现在只有一种整型——int，但它的行为就像2.X版本的long </p>
<p>2）新增了bytes类型，对应于2.X版本的八位串，定义一个bytes字面量的方法如下： 
    &gt;&gt;&gt; b = b'china' 
    &gt;&gt;&gt; type(b) 
    <type> 
str对象和bytes对象可以使用.encode() (str -&gt; bytes) or .decode() (bytes -&gt; str)方法相互转化。 
    &gt;&gt;&gt; s = b.decode() 
    &gt;&gt;&gt; s 
    'china' 
    &gt;&gt;&gt; b1 = s.encode() 
    &gt;&gt;&gt; b1 
    b'china' 
3）dict的.keys()、.items 和.values()方法返回迭代器，而之前的iterkeys()等函数都被废弃。同时去掉的还有 </type></p>
<p>dict.has_key()，用 in替代它吧 </p>
<p>6.面向对象 </p>
<p>1）引入抽象基类（Abstraact Base Classes，ABCs）。 </p>
<p>2）容器类和迭代器类被ABCs化，所以cellections模块里的类型比Py2.5多了很多。 
    &gt;&gt;&gt; import collections 
    &gt;&gt;&gt; print('n'.join(dir(collections))) 
    Callable 
    Container 
    Hashable 
    ItemsView 
    Iterable 
    Iterator 
    KeysView 
    Mapping 
    MappingView 
    MutableMapping 
    MutableSequence 
    MutableSet 
    NamedTuple 
    Sequence 
    Set 
    Sized 
    ValuesView 
    <strong>all</strong> 
    <strong>builtins</strong> 
    <strong>doc</strong> 
    <strong>file</strong> 
    <strong>name</strong> 
    _abcoll 
    _itemgetter 
    _sys 
    defaultdict 
    deque 
另外，数值类型也被ABCs化。关于这两点，请参阅 PEP 3119和PEP 3141。 </p>
<p>3）迭代器的next()方法改名为__next__()，并增加内置函数next()，用以调用迭代器的__next__()方法 </p>
<p>4）增加了@abstractmethod和 @abstractproperty两个 decorator，编写抽象方法（属性）更加方便。 </p>
<p>7.异常 </p>
<p>1）所以异常都从 BaseException继承，并删除了StardardError </p>
<p>2）去除了异常类的序列行为和.message属性 </p>
<p>3）用 raise Exception(args)代替 raise Exception, args语法 </p>
<p>4）捕获异常的语法改变，引入了as关键字来标识异常实例，在Py2.5中： 
    &gt;&gt;&gt; try: 
    ...    raise NotImplementedError('Error') 
    ... except NotImplementedError, error:
    ...    print error.message 
    ... 
    Error 
在Py3.0中： 
    &gt;&gt;&gt; try: 
          raise NotImplementedError('Error') 
        except NotImplementedError as error: #注意这个 as 
          print(str(error)) 
    Error 
5）异常链，因为__context__在3.0a1版本中没有实现 </p>
<p>8.模块变动 </p>
<p>1）移除了cPickle模块，可以使用pickle模块代替。最终我们将会有一个透明高效的模块。 </p>
<p>2）移除了imageop模块 </p>
<p>3）移除了 audiodev, Bastion, bsddb185, exceptions, linuxaudiodev, md5, MimeWriter, mimify, popen2,  </p>
<p>rexec, sets, sha, stringold, strop, sunaudiodev, timing和xmllib模块 </p>
<p>4）移除了bsddb模块(单独发布，可以从http://www.jcea.es/programacion/pybsddb.htm 获取) </p>
<p>5）移除了new模块 </p>
<p>6）os.tmpnam()和os.tmpfile()函数被移动到tmpfile模块下 </p>
<p>7）tokenize模块现在使用bytes工作。主要的入口点不再是generate_tokens，而是 tokenize.tokenize() </p>
<p>9.其它 </p>
<p>1）xrange() 改名为range()，要想使用range()获得一个list，必须显式调用： 
    &gt;&gt;&gt; list(range(10)) 
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 
2）bytes对象不能hash，也不支持 b.lower()、b.strip()和b.split()方法，但对于后两者可以使用 b.strip(b’  </p>
<p>ntr f’)和b.split(b’ ‘)来达到相同目的 </p>
<p>3）zip()、map()和filter()都返回迭代器。而apply()、 callable()、coerce()、execfile()、reduce()和reload </p>
<p>()函数都被去除了</p>
<p>现在可以使用hasattr()来替换 callable(). hasattr()的语法如：hasattr(string, '<strong>name</strong>')</p>
<p>4）string.letters和相关的.lowercase和.uppercase被去除，请改用string.ascii_letters 等 </p>
<p>5）如果x &gt;&gt; file 
    <type> 
在Py3.X中： 
    &gt;&gt;&gt; file 
    Traceback (most recent call last): 
    File "<pyshell>", line 1, in <module> 
       file 
    NameError: name 'file' is not defined</module></pyshell></type></p>
</div>
    </div>
    </article><article class="h-entry post-text"><header><h1 class="p-name entry-title"><a href="posts/python-capchar.html" class="u-url">python-capchar</a></h1>
        <div class="metadata">
            <p class="byline author vcard"><span class="byline-name fn">
                Tao Junjie
            </span></p>
            <p class="dateline"><a href="posts/python-capchar.html" rel="bookmark"><time class="published dt-published" datetime="2010-01-01T13:44:27+08:00" title="2010-01-01 13:44">2010-01-01 13:44</time></a></p>
        </div>
    </header><div class="p-summary entry-summary">
    <div>
<p></p>
<p>目标：CMDST价格监测</p>
<p class="more"><a href="posts/python-capchar.html">Read more…</a></p>
</div>
    </div>
    </article><article class="h-entry post-text"><header><h1 class="p-name entry-title"><a href="posts/python-cwd.html" class="u-url">python-cwd</a></h1>
        <div class="metadata">
            <p class="byline author vcard"><span class="byline-name fn">
                Tao Junjie
            </span></p>
            <p class="dateline"><a href="posts/python-cwd.html" rel="bookmark"><time class="published dt-published" datetime="2010-01-01T13:44:27+08:00" title="2010-01-01 13:44">2010-01-01 13:44</time></a></p>
        </div>
    </header><div class="p-summary entry-summary">
    <div>
<p></p>
<p>在python的一些程序执行时，CWD很重要：除非程序执行所需文件的名字都包含绝对目录路径，否则那些文件通常都被假设位于CWD里面。
记住，没有完整路径名的文件名映射到CWD，与PYTHONPATH设置无关。</p>
<p>1）一个程序是从CWD启动，而不是从包含它的目录启动；</p>
<p>2）import从包含程序的目录开始搜索，不是CWD。</p>
<p>当你在命令行输入这段命令：python dir1dir2file.py，CWD是输入命令的目录，可能是C:Documents and SettingsAdministrator，但不一定是file.py所在目录。另外，python会自动把file.py所在的目录绝对路径dir1dir2放在模块搜索路径最前面，这样不管在哪儿运行程序，file.py都可以导入dir1dir2内的所有文件。dir1dir2将成为模块搜索路径的第一路径。</p>
<p>实现from PP4E.System.more import more，需要之前在sys.path中加入（append）包含PP4E的目录。</p>
</div>
    </div>
    </article><article class="h-entry post-text"><header><h1 class="p-name entry-title"><a href="posts/python-gbk-link.html" class="u-url">python-gbk-link</a></h1>
        <div class="metadata">
            <p class="byline author vcard"><span class="byline-name fn">
                Tao Junjie
            </span></p>
            <p class="dateline"><a href="posts/python-gbk-link.html" rel="bookmark"><time class="published dt-published" datetime="2010-01-01T13:44:27+08:00" title="2010-01-01 13:44">2010-01-01 13:44</time></a></p>
        </div>
    </header><div class="p-summary entry-summary">
    <div>
<p></p>
<p>用urllib.request.urlopen(url) 打开有中文的网址的时候会报错
解决方法：</p>
<p>import urllib.parse</p>
<p>将中文 urllib.parse.quote("中文字符",encoding='GBK') </p>
<p>在调用urllib.request.urlopen(url)即可</p>
<p>即 strurl='http://'localhost/test.php?parm='+urllib.parse.quote("我是中文",encoding='GBK')</p>
<p>urllib.request.urlopen(strurl)</p>
</div>
    </div>
    </article><article class="h-entry post-text"><header><h1 class="p-name entry-title"><a href="posts/python-nest-forms.html" class="u-url">python-nest-forms</a></h1>
        <div class="metadata">
            <p class="byline author vcard"><span class="byline-name fn">
                Tao Junjie
            </span></p>
            <p class="dateline"><a href="posts/python-nest-forms.html" rel="bookmark"><time class="published dt-published" datetime="2010-01-01T13:44:27+08:00" title="2010-01-01 13:44">2010-01-01 13:44</time></a></p>
        </div>
    </header><div class="p-summary entry-summary">
    <div>
<p></p>
<code>
def list_or_tuple(x):
<p>return isinstance(x, (list, tuple))</p>
<p>def flatten(sequence, to_expand=list_or_tuple):</p>
<p>for item in sequence:</p>
<p>if to_expand(item):</p>
<p>for subitem in flatten(item, to_expand):</p>
<p>yield subitem</p>
<p>else:</p>
<p>yield item</p></code>
</div>
    </div>
    </article>
</div>

        <nav class="postindexpager"><ul class="pager">
<li class="previous">
                <a href="index-4.html" rel="prev">Newer posts</a>
            </li>
            <li class="next">
                <a href="index-2.html" rel="next">Older posts</a>
            </li>
        </ul></nav>
</div>
        <!--End of body content-->

        <footer id="footer">
            Contents © 2017         <a href="mailto:muxuezi@gmail.com">Tao Junjie</a> - Powered by         <a href="https://getnikola.com" rel="nofollow">Nikola</a>         
<a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0">
<img alt="Creative Commons License BY-NC-SA" style="border-width:0; margin-bottom:12px;" src="http://i.creativecommons.org/l/by-nc-sa/4.0/80x15.png"></a>
            
        </footer>
</div>
</div>


            <script src="assets/js/all-nocdn.js"></script><script>$('a.image-reference:not(.islink) img:not(.islink)').parent().colorbox({rel:"gal",maxWidth:"100%",maxHeight:"100%",scalePhotos:true});</script><!-- fancy dates --><script>
    moment.locale("en");
    fancydates(0, "YYYY-MM-DD HH:mm");
    </script><!-- end fancy dates --><script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-51330059-1', 'auto');
  ga('send', 'pageview');

</script>
</body>
</html>
